﻿// MIT License
//
// Copyright (c) 2021-present zuohuaijun, Daming Co.,Ltd and Contributors
//
// 电话/微信：18020030720 QQ群1：87333204 QQ群2：252381476

using Admin.NET.Application.Const;
using Admin.NET.Core;
using Admin.Net.InformationPlatform.Entity;
using Admin.Net.InformationPlatform.Service.Order.Dto;
using Admin.Net.InformationPlatform.Service.Product.Dto.T100;
using Admin.Net.InformationPlatform.Service.Product.Dto.View;
using Admin.Net.InformationPlatform.Service.Product.Dto;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Microsoft.AspNetCore.Mvc;
using Nest;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Admin.Net.InformationPlatform.Service.Equipment.Dto;
using Admin.Net.InformationPlatform.Service.Equipment_Para.Dto;
using Admin.Net.InformationPlatform.Service.Product.Dto.user;
using Admin.Net.InformationPlatform.Entity.ProdectFile;
using Admin.Net.InformationPlatform.Entity.Order;
using Admin.Net.InformationPlatform.Entity.Equipment;

namespace Admin.Net.InformationPlatform.Service.Product;
/// <summary>
/// 客户下单ceshi 
/// </summary>
[ApiDescriptionSettings(groups: "PlaceOrder", Name = "在线下单1", Tag = "客户信息处理1", Order = 200)]
public class OrderCustomerService1 : IDynamicApiController, ITransient
{
    /// <summary>
    /// 单例数据链接
    /// </summary>
    ISqlSugarClient db;
    /// <summary>
    /// T100数据库
    /// </summary>
    private SqlSugarProvider _T100Db;
    private SqlSugarProvider _SjDb;
    private SqlSugarProvider _plm;
    private SqlSugarProvider _Dilon;
    private SqlSugarProvider _T100TestView;


    /// <summary>
    /// 用户信息
    /// </summary>
    TokenUser _User;
    /// <summary>
    /// 报备客户管理模块
    /// </summary>
    /// <param name="db"></param>
    public OrderCustomerService1(ISqlSugarClient db)
    {
        this.db = db;
        this._T100Db = this.db.AsTenant().GetConnection(T100Const.ConfigId);
        this._SjDb = this.db.AsTenant().GetConnection(SJDB.ConfigId);
        this._plm = this.db.AsTenant().GetConnection(PLM.ConfigId);
        this._Dilon = this.db.AsTenant().GetConnection(Dilon.ConfigId);
        this._T100TestView = this.db.AsTenant().GetConnection(T100TestView.ConfigId);
        // 获取 `Jwt` 存储的信息 企业编号与据点信息
        _User = Util.SjCommonUtil.GetT100UserTokenInfo(_T100Db, _Dilon);

    }

    /// <summary>
    /// 生成不重复订单号
    /// </summary>
    /// <returns></returns>
    private string GetOrderNo1()
    {

        TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);

        string orderNo = DateTime.Now.Date.ToString("yyyyMMdd") + Convert.ToInt64(ts.TotalSeconds).ToString();

        return orderNo;
    }


    /// <summary>
    /// 客户编号模糊查询
    /// </summary>
    /// <param name="user"></param>
    /// <returns></returns>
    [HttpPost("/Order/GetUserMessage1")]
    public async Task<List<UserMessage>> SelectUserNameMessage1([FromBody] UserMessageInput user)
    {

        //权限验证
        var LoginRoles = _Dilon.Queryable<SysUserRole>()
                .LeftJoin<SysUser>((r, u) => (r.UserId == u.Id))
                      .Where((r, u) => r.UserId.ToString() == _User.ID)
                     .Select((r, u) => new SalesmanRole
                     {
                         USERID = u.Account,
                         USERNAME = u.RealName,
                         ROLEID = r.RoleId.ToString()
                     }).ToList();
        int role = LoginRoles.Where(u => u.ROLEID == "14631543922501").Count();//判断是否拥有营销中心角色
        int role1 = LoginRoles.Where(u => u.ROLEID == "14620909947205").Count();//判断是否拥有销售助理角色


        //List<T100UserMessage> t100List = _T100TestView.Ado.SqlQuery<T100UserMessage>($@"WITH RecursiveCTE AS(
        //        SELECT lastname,
        //            ID, managerid
        //        FROM HrmResource
        //        WHERE ID = (SELECT id from HrmResource where loginid = '007637')-- 将 @YourID 替换为您要查询的根 ID
        //        UNION ALL
        //        SELECT yt.lastname,yt.ID, yt.managerid
        //        FROM HrmResource yt
        //        JOIN RecursiveCTE cte ON yt.managerid = cte.ID
        //    )
        //    SELECT lastname,
        //    ID, managerid
        //    FROM RecursiveCTE;").ToList();





        List<string> a = new List<string>();

        //销售总监 能看到全部数据
        if (role > 0)
        {
            //查询城市经理下的业务员信息
            var values = _Dilon.Queryable<SysUserRole>()
                .LeftJoin<SysUser>((r, u) => (r.UserId == u.Id))
                .Where((r, u) => r.RoleId.ToString() == "14620909947205")
                .Where((r, u) => u.OrgId.ToString() == _User.OrgId)
                 .Select((r, u) => new SalesmanRoles
                 {
                     BBR = u.Account,
                 }).ToList();

            for (int i = 0; i < values.Count; i++)
            {
                a.Add(values[i].BBR);
            }
        }

        //销售助理角色
        if (role1 > 0)
        {



            //查询城市经理下的业务员信息
            var values = _Dilon.Queryable<SysUserRole>()
                .LeftJoin<SysUser>((r, u) => (r.UserId == u.Id))
                .Where((r, u) => r.RoleId.ToString() == "14620909947205")
                .Where((r, u) => u.OrgId.ToString() == _User.OrgId)
                 .Select((r, u) => new SalesmanRoles
                 {
                     BBR = u.Account,
                 }).ToList();

            for (int i = 0; i < values.Count; i++)
            {
                a.Add(values[i].BBR);
            }
        }


        //中间职位只能看到自己和对应下级的数据
        if (role == 0 && role1 == 0)
        {
            //查询城市经理下的业务员信息
            var values = _Dilon.Queryable<SysUserRole>()
                .LeftJoin<SysUser>((r, u) => (r.UserId == u.Id))
                .Where((r, u) => r.RoleId.ToString() == "14478138094149")
                .Where((r, u) => u.OrgId.ToString() == _User.OrgId)
                 .Select((r, u) => new SalesmanRoles
                 {
                     BBR = u.Account,
                 }).ToList();

            for (int i = 0; i < values.Count; i++)
            {
                a.Add(values[i].BBR);
            }
        }


        var viewList = await _T100TestView.Queryable<DHAXMT200_VIEW_PMABENT>()
             .Where(it => it.DHPMAB007.Contains(user.UserName))
             //  .WhereIF(role == 1, (l) => l.DHPMAB006 == _User.UserId)//业务员只能看自己的数据
             //  .WhereIF(role1 == 1, (l) => a.Contains(l.DHPMAB006))//城市经理可以看到自己名下业务员数据
             .Select(a => new UserMessage
             {
                 UserNo = a.DHPMAB006,
                 UserName = a.DHPMAB007

             }).ToListAsync();

        return viewList;

    }

    /// <summary>
    /// /根据客户简称查询
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost("/Order/GetCustomerMessagetest")]
    public UserMessageOut GetCustomerMessagetest([FromBody] Admin.Net.InformationPlatform.Service.Product.Dto.CustomerInput input)
    {

        //缺了一个部门下属的验证

        List<Cxmm200View> viewList = _T100TestView.Ado.SqlQuery<Cxmm200View>($@"select * from cxmm200_view where cxmm200_view002='{input.CustName}'").ToList();

        if (viewList.Count == 0)
        {
            return null;
        }

        List<DHAXMM200_CUSTOMS008> DHAXMM200_CUSTOMS008 = _T100TestView.Ado.SqlQuery<DHAXMM200_CUSTOMS008>($@"select * from DHAXMM200_customs008 where pmaa001='{viewList[0].CXMM200_VIEW001}'").ToList();

        List<DHAXMT200_VIEW_PMAD002> DHAXMT200_VIEW_PMAD002 = _T100TestView.Ado.SqlQuery<DHAXMT200_VIEW_PMAD002>($@"select * from DHAXMT200_VIEW_PMAD002 where DHPMAD001='{viewList[0].CXMM200_VIEW001}'").ToList();
        if (DHAXMT200_VIEW_PMAD002.Count == 0)
        {
            throw Oops.Oh("请填写收款条件！");
        }

        List<DHAXMM202_CUSTOMS005> DHAXMM202_CUSTOMS005 = _T100TestView.Ado.SqlQuery<DHAXMM202_CUSTOMS005>($@"select * from DHAXMM202_customs005 where PMAB001='{viewList[0].CXMM200_VIEW001}'").ToList();

        if (DHAXMM202_CUSTOMS005.Count == 0)
        {
            throw Oops.Oh("请填写客户惯用交易币种！");
        }
        UserMessageOut userMessage = new UserMessageOut();
        userMessage.UserNo = viewList[0].CXMM200_VIEW001;//用户编号
        userMessage.UserName = viewList[0].CXMM200_VIEW002;//用户名称
        userMessage.CustNumber = this.GetOrderNo1(); //订单编号
        userMessage.OrderDate = DateTime.Now.Date.ToString("yyyy-MM-dd");//订单日期
        userMessage.CustNo = viewList[0].CXMM200_VIEW021;//默认业务员编号
        userMessage.CustName = viewList[0].CXMM200_VIEW022;//默认业务员名称
        userMessage.UserDepartment = viewList[0].CXMM200_VIEW023;//业务部门编号
        userMessage.UserDepartmentName = viewList[0].CXMM200_VIEW024;//业务部门名称
        userMessage.OrderData = 1; //订单性质编号
        userMessage.OrderDataName = "一般订单";//订单性质 待定
        userMessage.OrderType = "XM61";//订单类型编号 待定
        userMessage.OrderTypeName = "其他客户订单";//订单类型 待定
        userMessage.CheckStatus = DHAXMM200_CUSTOMS008[0].PMACSTUS.Equals("Y") ? "已审核" : "未审核";//审核状态
        userMessage.TaxType = DHAXMT200_VIEW_PMAD002[0].DHPMAD005;//收款条件
        userMessage.TaxTypeName = DHAXMT200_VIEW_PMAD002[0].DHPMAD006;//收款条件名称
        userMessage.CoinType = DHAXMM202_CUSTOMS005.Count > 0 ? DHAXMM202_CUSTOMS005[0].pmab083 : "";//币种
        userMessage.CoinTypeName = DHAXMM202_CUSTOMS005.Count > 0 ? DHAXMM202_CUSTOMS005[0].ooail003 : "";//币种信息
        userMessage.GetPriceType = viewList[0].CXMM200_VIEW042; //取价方式
        userMessage.GetPriceTypeName = viewList[0].CXMM200_VIEW043;//取价方式名称
        return userMessage;
    }

    /// <summary>
    /// 在线下单（根据客户简称查询）
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost("/Order/GetCustomerMessage1")]
    public async Task<UserMessageOut> GetCustomerMessage1(GetCustomerMessage input)
    {
        //判断当前登录人是否拥有可以查看此客户简称的权限
        //判断单据存在
        int cnt = await _SjDb.Queryable<XD_USER_ACCREDIT>()
            .Where(a => a.KHJC == input.CustName)
            .Where(a => a.ISDELETE == 0)
            .Where(a => a.USERID == _User.UserId)
            .Select(a => a.ID)
            .CountAsync();
        if (cnt == 0)
        {
            throw Oops.Oh("客户不存在！");
        }

        //缺了一个部门下属的验证

        List<Cxmm200View> viewList = _T100TestView.Ado.SqlQuery<Cxmm200View>($@"select * from cxmm200_view where cxmm200_view002='{input.CustName}'").ToList();

        if (viewList.Count == 0)
        {
            return null;
        }

        List<DHAXMM200_CUSTOMS008> DHAXMM200_CUSTOMS008 = _T100TestView.Ado.SqlQuery<DHAXMM200_CUSTOMS008>($@"select * from DHAXMM200_customs008 where pmaa001='{viewList[0].CXMM200_VIEW001}'").ToList();

        List<DHAXMT200_VIEW_PMAD002> DHAXMT200_VIEW_PMAD002 = _T100TestView.Ado.SqlQuery<DHAXMT200_VIEW_PMAD002>($@"select * from DHAXMT200_VIEW_PMAD002 where DHPMAD001='{viewList[0].CXMM200_VIEW001}'").ToList();
        if (DHAXMT200_VIEW_PMAD002.Count == 0)
        {
            throw Oops.Oh("请填写收款条件！");
        }

        List<DHAXMM202_CUSTOMS005> DHAXMM202_CUSTOMS005 = _T100TestView.Ado.SqlQuery<DHAXMM202_CUSTOMS005>($@"select * from DHAXMM202_customs005 where PMAB001='{viewList[0].CXMM200_VIEW001}'").ToList();

        if (DHAXMM202_CUSTOMS005.Count == 0)
        {
            throw Oops.Oh("请填写客户惯用交易币种！");
        }
        UserMessageOut userMessage = new UserMessageOut();
        userMessage.UserNo = viewList[0].CXMM200_VIEW001;//用户编号
        userMessage.UserName = viewList[0].CXMM200_VIEW002;//用户名称
        userMessage.CustNumber = this.GetOrderNo1(); //订单编号
        userMessage.OrderDate = DateTime.Now.Date.ToString("yyyy-MM-dd");//订单日期
        userMessage.CustNo = viewList[0].CXMM200_VIEW021;//默认业务员编号
        userMessage.CustName = viewList[0].CXMM200_VIEW022;//默认业务员名称
        userMessage.UserDepartment = viewList[0].CXMM200_VIEW023;//业务部门编号
        userMessage.UserDepartmentName = viewList[0].CXMM200_VIEW024;//业务部门名称
        userMessage.OrderData = 1; //订单性质编号
        userMessage.OrderDataName = "一般订单";//订单性质 待定
        userMessage.OrderType = "XM61";//订单类型编号 待定
        userMessage.OrderTypeName = "其他客户订单";//订单类型 待定
        userMessage.CheckStatus = DHAXMM200_CUSTOMS008[0].PMACSTUS.Equals("Y") ? "已审核" : "未审核";//审核状态
        userMessage.TaxType = DHAXMT200_VIEW_PMAD002[0].DHPMAD005;//收款条件
        userMessage.TaxTypeName = DHAXMT200_VIEW_PMAD002[0].DHPMAD006;//收款条件名称
        userMessage.CoinType = DHAXMM202_CUSTOMS005.Count > 0 ? DHAXMM202_CUSTOMS005[0].pmab083 : "";//币种
        userMessage.CoinTypeName = DHAXMM202_CUSTOMS005.Count > 0 ? DHAXMM202_CUSTOMS005[0].ooail003 : "";//币种信息
        userMessage.GetPriceType = viewList[0].CXMM200_VIEW042; //取价方式
        userMessage.GetPriceTypeName = viewList[0].CXMM200_VIEW043;//取价方式名称
        return userMessage;
    }

    /// <summary>
    /// 客户列表（分页）
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost("/Order/GetCustomerList")]
    public async Task<SqlSugarPagedList<UserOutPut>> GetCustomerList(UserInput input)
    {

        string sql = " where 1=1 ";
        if (!string.IsNullOrEmpty(input.USERID))
            sql += $@" and account like '%{input.USERID}%'";
        if (!string.IsNullOrEmpty(input.NAME))
            sql += $@" and realname like '%{input.NAME}%'";

        return _Dilon.Ado.SqlQuery<UserOutPut>($@"
           SELECT u.* ,o.name orgname from SysUser u
left join SysOrg o on u.OrgId = o.Id
 where u.id in (select UserId from  SysUserRole where RoleId in 
('14631543922501','14620922269125','14620909947205','14555217627205','14555212310213','14478138094149')) {sql}
                ").ToPagedList(input.Page, input.PageSize);


    }

    /// <summary>
    /// 根据客户编号查询授权客户
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost("/Order/GetCustomData")]
    public async Task<string> GetCustomData(UserData input)
    {
        string sql = " where 1=1 ";
        if (!string.IsNullOrEmpty(input.KHH))
            sql += $@" and cxmm200_view001 like '%{input.KHH}%'";
        //if (!string.IsNullOrEmpty(input.KHJC))
        //    sql += $@" and cxmm200_view002 realname like '%{input.KHJC}%'";
        List<UserDataByName> viewList = _T100TestView.Ado.SqlQuery<UserDataByName>($@"select cxmm200_view001 KHH,cxmm200_view002 KHJC,cxmm200_view057 KHQC from cxmm200_view {sql}").ToList();
        if (viewList.Count == 0)
        {
            throw Oops.Oh($"该客户不存在！");
        }
        //判断授权客户是否存在
        int cnt1 = await _SjDb.Queryable<XD_USER_ACCREDIT>()
             .Where(l => l.ISDELETE == 0)
             .Where(l => l.KHH == input.KHH)
            .Select(l => l.ID)
            .CountAsync();
        //授权客户已存在直接返回
        if(cnt1>0) 
        {
            return "操作成功！";
        }
        var details = new XD_USER_ACCREDIT
        {
            ID = Guid.NewGuid().ToString("N"),
            KHH  = viewList[0].KHH,
            KHJC  = viewList[0].KHJC,
            KHQC  = viewList[0].KHQC,
            CREATETIME = DateTime.Now,
            ISDELETE = 0,
            USERID = input.USERID,
            REALNAME =input.USERNAME
        };
     
        #region 插入事务
        try
        {
            //开启事务
            _SjDb.Ado.BeginTran();
            int cnt = await _SjDb.Insertable<XD_USER_ACCREDIT>(details).ExecuteCommandAsync();

            if (cnt == 0)
            {
                throw Oops.Oh($"新建任务失败！");
            }
            //提交事务
            _SjDb.Ado.CommitTran();
            return "操作成功！";
        }
        catch (Exception e)
        {
            //回滚事务
            _SjDb.Ado.RollbackTran();
            throw Oops.Oh($"异常：{e.Message}");
        }
        #endregion
    }
    /// <summary>
    /// 根据用户查询客户授权列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost("/Order/UserAccreditList")]
    public async Task<SqlSugarPagedList<XD_USER_ACCREDIT>> UserAccreditList(AccreditList input)
    {
        var output = await _SjDb.Queryable<XD_USER_ACCREDIT>()
.Where(l => l.ISDELETE == 0)
.Where((l) => (l.USERID == input.USERID))//用户ID
.OrderBy(l => l.CREATETIME, OrderByType.Desc) //创建时间排序
.Select(l => new XD_USER_ACCREDIT
{
    ID = l.ID,
    KHH = l.KHH,
    KHJC = l.KHJC,
    CREATETIME = l.CREATETIME,
    KHQC = l.KHQC,
    USERID = l.USERID,
    REALNAME = l.REALNAME,
}).ToPagedListAsync(input.Page, input.PageSize);
        return output;
    }

    /// <summary>
    /// 授权客户删除
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost("/Order/DeleteAccredit")]
    public async Task<string> DeleteAccredit(DeleteAccredit input)
    {
        //判断单据存在
        int cnt = await _SjDb.Queryable<XD_USER_ACCREDIT>()
            .Where(a => a.ID == input.ID)
            .Select(a => a.ID)
            .CountAsync();
        if (cnt == 0)
        {
            throw Oops.Oh("任务不存在，驳回！");
        }
        else
        {
            //提交
            try
            {
                _SjDb.Ado.BeginTran();
                int count = await _SjDb.Updateable<XD_USER_ACCREDIT>()
                    .SetColumns(a => a.ISDELETE == 1)
                    .Where(a => a.ID == input.ID)
                    .ExecuteCommandAsync();


                if (count != 1)
                {
                    throw Oops.Oh("删除失败！");
                }
                _SjDb.Ado.CommitTran();
                return "删除成功！";
            }
            catch (Exception e)
            {
                _SjDb.Ado.RollbackTran();
                throw Oops.Oh($"异常：{e.Message}");
            }
        }
    }

    /// <summary>
    /// 用户列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost("/Order/UserAccredit")]
    public async Task<SqlSugarPagedList<UserOutPut>> UserAccredit(SelectEquipmentBasicInput input)
    {

        string sql = "";
        if (!string.IsNullOrEmpty(input.DEVICENUMBER))
            sql += $@" and b.DEVICE_NUMBER like '%{input.DEVICENUMBER}%'";
        return _Dilon.Ado.SqlQuery<UserOutPut>($@"
           SELECT u.* ,o.name orgname from SysUser u
left join SysOrg o on u.OrgId = o.Id
 where u.id in (select UserId from  SysUserRole where RoleId in 
('14631543922501','14620922269125','14620909947205','14555217627205','14555212310213','14478138094149'))
                ").ToPagedList(input.Page, input.PageSize);


    }
}
